package omm.domain;

import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;

import omm.domain.exceptions.DatabaseException;

import org.springframework.stereotype.Component;

@Component
public class ConnectionManager {
	
	private static ConnectionManager instance;
	
	private String username;
	private String password;
	private String connectionString;
	private String driver;
	
	public ConnectionManager(String connectionString, String username, String password, String driver){
		this.connectionString = connectionString;
		this.username = username;
		this.password = password;
		this.driver = driver;
		try{
			Class.forName(driver);
		}catch(ClassNotFoundException e){
			throw new DatabaseException();
		}
	}
	
	private void loadParameters(){
		Properties properties = new Properties();
		try { 
			properties.load(getClass().getClassLoader().getResourceAsStream("setup.properties"));
			username = properties.getProperty("username");
			password = properties.getProperty("password");
			connectionString = properties.getProperty("connectionString");
		} catch (IOException e) { 
			throw new DatabaseException();
		}
	}
	
	public Connection getConnection(){
		Connection connection;
		try {
			connection = DriverManager.getConnection(connectionString, username, password);
			connection.setAutoCommit(false);
		} catch (SQLException e) {
			throw new DatabaseException();
		}
		return connection;
	}

	public void closeConnection(Connection connection)
	{
		try
		{
			connection.commit();
			connection.close();
		}
		catch(Exception e)
		{
			throw new DatabaseException();
		}
	}
}